package org.platform.service.knowledge;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mc.mic.core.log.bus.BusLogPusher;
import com.mc.mic.core.log.frame.LogBo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.platform.constant.LogType;
import org.platform.constant.StationConst;
import org.platform.dao.mapper.*;
import org.platform.mo.bussmo.diagnose.event.AlarmBO;
import org.platform.mo.bussmo.log.OperationMqBO;
import org.platform.mo.csmo.cmd10001.EventGroupQueryRequestParam;
import org.platform.mo.csmo.cmd10001.EventGroupQueryResponseParam;
import org.platform.mo.csmo.cmd10002.EventGroupAddRequestParam;
import org.platform.mo.csmo.cmd10002.EventGroupAddResponseParam;
import org.platform.mo.csmo.cmd10003.EventGroupDelRequestParam;
import org.platform.mo.csmo.cmd10003.EventGroupDelResponseParam;
import org.platform.mo.csmo.cmd10004.EventGroupModifyRequestParam;
import org.platform.mo.csmo.cmd10004.EventGroupModifyResponseParam;
import org.platform.mo.csmo.cmd10005.EventQueryRequestParam;
import org.platform.mo.csmo.cmd10005.EventQueryResponseParam;
import org.platform.mo.csmo.cmd10006.EventAddRequestParam;
import org.platform.mo.csmo.cmd10006.EventAddResponseParam;
import org.platform.mo.csmo.cmd10007.EventDelRequestParam;
import org.platform.mo.csmo.cmd10007.EventDelResponseParam;
import org.platform.mo.csmo.cmd10008.EventModifyRequestParam;
import org.platform.mo.csmo.cmd10008.EventModifyResponseParam;
import org.platform.mo.csmo.cmd10026.QueryAlarmEventRequestParam;
import org.platform.mo.csmo.cmd10026.QueryAlarmEventResponseParam;
import org.platform.mo.csmo.common.KB_Monitor;
import org.platform.mo.csmo.common.KB_MonitorGroup;
import org.platform.mo.db.*;
import org.platform.service.IBaseService;
import org.platform.tool.helper.LogHelper;
import org.platform.tool.util.BeansUtils;
import org.platform.tool.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author: FengJie
 * @Date: 2018/3/30 10:38
 */
@Service
@Slf4j
public class EventServiceImpl implements IBaseService {
    @Autowired
    private FdKbEventMapper eventMapper;
    @Autowired
    private FdKbEventgroupMapper eventGroupMapper;
    @Autowired
    private FdSanyaEventMapper syMapper;
    @Autowired
    private FdMiyunEventMapper myMapper;
    @Autowired
    private FdKashiEventMapper ksMapper;
    @Autowired
    private FdXinanEventMapper xnMapper;

    @Autowired
    private BusLogPusher mqLog;
    @Autowired
    private LogHelper logHelper;

    /**
     * 查询当前的监测点组（10001）
     */
    public EventGroupQueryResponseParam queryEventGroup(EventGroupQueryRequestParam requestParam) {
        EventGroupQueryResponseParam responseParam = new EventGroupQueryResponseParam();

        List<FdKbEventgroup> eventGroupList = eventGroupMapper.selectAll();
        List<KB_MonitorGroup> monitorGroupList = BeansUtils.copyListProperties(eventGroupList, KB_MonitorGroup.class);

        responseParam.setGroupList(monitorGroupList);
        return responseParam;
    }

    /**
     * 增加某个监测点组（10002）
     */
    public EventGroupAddResponseParam addEventGroup(EventGroupAddRequestParam requestParam) {
        try {
            KB_MonitorGroup group = requestParam.getGroup();
            FdKbEventgroup eventGroup = new FdKbEventgroup();
            BeanUtils.copyProperties(group, eventGroup);
            eventGroupMapper.insert(eventGroup);
            logHelper.normal("增加监测点组【成功】", null, null);
        } catch (RuntimeException e) {
            logHelper.error("增加监测点组【失败】", null, null, e);
        }
        return new EventGroupAddResponseParam();
    }

    /**
     * 删除某个监测点组（10003）
     */
    public EventGroupDelResponseParam delEventGroup(EventGroupDelRequestParam requestParam) {
        try {
            String groupID = requestParam.getGroupID();
            Example example = new Example(FdKbEventgroup.class);
            example.createCriteria().andEqualTo("groupid", groupID);
            eventGroupMapper.deleteByExample(example);
            logHelper.normal("删除监测点组【成功】", null, null);
        } catch (RuntimeException e) {
            logHelper.error("删除监测点组【失败】", null, null, e);
        }
        return new EventGroupDelResponseParam();
    }

    /**
     * 修改某个监测点组（10004）
     */
    public EventGroupModifyResponseParam modifyEventGroup(EventGroupModifyRequestParam requestParam) {
        try {
            KB_MonitorGroup group = requestParam.getGroup();
            FdKbEventgroup eventGroup = new FdKbEventgroup();
            BeanUtils.copyProperties(group, eventGroup);
            eventGroupMapper.updateByPrimaryKeySelective(eventGroup);
            logHelper.normal("修改监测点组【成功】", null, null);
        } catch (RuntimeException e) {
            logHelper.error("修改监测点组【失败】", null, null, e);
        }
        return new EventGroupModifyResponseParam();
    }

    /**
     * 查询某个设备的监测点集合（10005）
     */
    public EventQueryResponseParam queryEvent(EventQueryRequestParam requestParam) {
        String deviceID = requestParam.getDeviceID();
        String station = requestParam.getStation();
        Example example = new Example(FdKbEvent.class);
        example.createCriteria()
                .andEqualTo("station", station)
                .andEqualTo("deviceid", deviceID);
        List<FdKbEvent> eventList = eventMapper.selectByExample(example);
        List<KB_Monitor> monitorList = BeansUtils.copyListProperties(eventList, KB_Monitor.class);
        EventQueryResponseParam responseParam = new EventQueryResponseParam();
        responseParam.setEventList(monitorList);
        return responseParam;
    }

    /**
     * 增加一个监测点（10006）
     */
    public EventAddResponseParam addEvent(EventAddRequestParam requestParam) {
        mqLog.log(new LogBo<>(LogType.OPERATION_LOG, new OperationMqBO("正在增加一个监测点")));
        KB_Monitor monitor = requestParam.getMonitor();
        FdKbEvent event = new FdKbEvent();
        BeanUtils.copyProperties(monitor, event);
        eventMapper.insert(event);
        return new EventAddResponseParam();
    }

    /**
     * 删除一个监测点（10007）
     */
    public EventDelResponseParam delEvent(EventDelRequestParam requestParam) {
        try {
            long[] eventIDList = requestParam.getEventIDList();
            Example example = new Example(FdKbEvent.class);
            Example.Criteria criteria = example.createCriteria();
            for (int i = 0; i < eventIDList.length; i++) {
                criteria.orEqualTo("knowledgeid", eventIDList[i]);
            }
            example.and(criteria);
            eventMapper.deleteByExample(example);
            logHelper.normal("删除单个监测点【成功】", null, null);
        } catch (RuntimeException e) {
            logHelper.error("删除单个监测点【失败】", null, null, e);
        }
        return new EventDelResponseParam();
    }

    /**
     * 修改一个监测点（10008）
     */
    public EventModifyResponseParam modifyEvent(EventModifyRequestParam requestParam) {
        try {
            KB_Monitor monitor = requestParam.getMonitor();
            FdKbEvent event = new FdKbEvent();
            BeanUtils.copyProperties(monitor, event);
            eventMapper.updateByPrimaryKeySelective(event);
            logHelper.normal("修改单个监测点【成功】", null, null);
        } catch (RuntimeException e) {
            logHelper.error("修改单个监测点【失败】", null, null, e);
        }
        return new EventModifyResponseParam();
    }

    /**
     * 查询告警表
     */
    public QueryAlarmEventResponseParam queryAlarmEvent(QueryAlarmEventRequestParam requestParam) {
        QueryAlarmEventResponseParam responseParam = new QueryAlarmEventResponseParam();
        Example example = new Example(FdSanyaEvent.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(requestParam.getDeviceID())) {
            criteria.andEqualTo("deviceid", requestParam.getDeviceID());
        }
        if (requestParam.getKnowledgeID() != -1) {
            criteria.andEqualTo("knowledgeid", requestParam.getKnowledgeID());
        }
        //c#表示的时间戳和java 的时间戳格式不同
        if (StringUtils.isNotEmpty(requestParam.getStartTime())) {
            criteria.andGreaterThanOrEqualTo("happendtime", TimeUtils.strTimeToTimestampsByFormat(requestParam.getStartTime(), null));
        }
        if (StringUtils.isNotEmpty(requestParam.getEndTime())) {
            criteria.andLessThanOrEqualTo("happendtime", TimeUtils.strTimeToTimestampsByFormat(requestParam.getEndTime(), null));
        }
        example.orderBy("happendtime").desc();

        List<AlarmBO> alarmEventList;
        Page<Object> page = PageHelper.startPage(requestParam.getPageNum(), requestParam.getPageSize());
        switch (requestParam.getStationName()) {
            case StationConst.KASHA_STATION:
                List<FdKashiEvent> ksList = ksMapper.selectByExample(example);
                alarmEventList = BeansUtils.copyListProperties(ksList, AlarmBO.class);
                break;
            case StationConst.MIYUN_STATION:
                List<FdMiyunEvent> myList = myMapper.selectByExample(example);
                alarmEventList = BeansUtils.copyListProperties(myList, AlarmBO.class);
                break;
            case StationConst.SANYA_STATION:
                List<FdSanyaEvent> syList = syMapper.selectByExample(example);
                alarmEventList = BeansUtils.copyListProperties(syList, AlarmBO.class);
                break;
            default:
                List<FdXinanEvent> xnList = xnMapper.selectByExample(example);
                alarmEventList = BeansUtils.copyListProperties(xnList, AlarmBO.class);
        }
        responseParam.setCount(page.getTotal());
        responseParam.setAlarmList(alarmEventList);
        return responseParam;
    }

}
